﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Uber.WebUI
{
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Web.Mvc;
    using xVal.ServerSide;

    public class MyModelBinder : IModelBinder
    {
        private readonly IModelBinder defaultBinder = new DefaultModelBinder();

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var boundInstance = defaultBinder.BindModel(controllerContext, bindingContext);

            if (boundInstance != null)
            {
                PerformValidation(boundInstance, bindingContext);
            }

            return boundInstance;
        }

        protected void PerformValidation(object instance, ModelBindingContext context)
        {
            var errors = GetErrors(instance);

            if (!errors.Any()) return;
            var rulesException = new RulesException(errors);
            rulesException.AddModelStateErrors(context.ModelState, null);
        }

        public static IEnumerable<ErrorInfo> GetErrors(object instance)
        {
            return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>()
                   from attribute in prop.Attributes.OfType<ValidationAttribute>()
                   where !attribute.IsValid(prop.GetValue(instance))
                   select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(String.Empty), instance);
        }

    }
}
